// Learn TypeScript:
//  - https://docs.cocos.com/creator/manual/en/scripting/typescript.html
// Learn Attribute:
//  - https://docs.cocos.com/creator/manual/en/scripting/reference/attributes.html
// Learn life-cycle callbacks:
//  - https://docs.cocos.com/creator/manual/en/scripting/life-cycle-callbacks.html

import config from "../config";
import global from "../global";
import FlyObj from "./FlyObj";

const { ccclass, property } = cc._decorator;

@ccclass
export default class SpaceShip extends FlyObj {
    @property({
        type: cc.AudioClip,
        tooltip: "grabsound",
        displayName: "grabsound",
    })
    gamegrabsound: cc.AudioClip = null;



    public anchorPlanet: NodeInfoPara = null;

    public radian: number = 0;
    public shipSpeed: number = 5;
    public circleRadius: number = 0;
    public isMoving: boolean = false;       // 飞船是否正在飞往下一处，飞行中点击事件无效
    public isDestroy: boolean = false;      // 飞船是否被摧毁
    // LIFE-CYCLE CALLBACKS:

    public supportLineNode: cc.Node = null;
    public supportLine: cc.Sprite = null;


    onLoad() {
        super.onLoad();
        this.node.name = "SpaceShip";
        this.nodeName = "SpaceShip";
        this.circleCollider.name = "SpaceShip";

        // console.log("SS onload");

        const anchorInfo: NodeInfoPara =
        {
            x: 0,
            y: 0,
            scaleX: 1,
            scaleY: 1,
            width: 60,
            height: 60
        };

        cc.resources.load('Audio/sub/grab', cc.AudioClip, (err, AudioClip) => {
            this.gamegrabsound = AudioClip;
        })

        // cc.assetManager.loadRemote(config.GameGrabSoundURL, { ext: '.mp3' }, (err, AudioClip) => {
        //     this.gamegrabsound = AudioClip;
        // })



        this.anchorPlanet = anchorInfo;
        this.setInfo(this.anchorPlanet);

        // this.setPhoto(config.spaceShipURL)
        this.setLocalPhoto("images/flyobj/UFO");
        // this.updateRadius();
        this.radian = - Math.PI / 2;
        // this.ObjSprite.node.setPosition(this.anchorPlanet.x, this.anchorPlanet.y - this.circleRadius);
        this.supportLineNode = new cc.Node;
        this.supportLineNode.setParent(this.node);
        this.supportLine = this.supportLineNode.addComponent(cc.Sprite);
        // cc.assetManager.loadRemote(config.supportLibeUrl, { ext: '.png' }, (err, texture) => {
        //     this.supportLine.spriteFrame = new cc.SpriteFrame(texture);
        // })

        // this.supportLineNode.opacity = 64;

        // var self = this;
        // cc.resources.load("images/ui/indicator", function (err, texture) {
        //     self.supportLine.spriteFrame = new cc.SpriteFrame(texture);
        // })
        // console.log(this.supportLineNode.width)
        // console.log(this.supportLineNode.height)
    }

    start() {
        super.start();
    }

    //update(dt){}

    shipMoving(dt) {
        if (this.isDestroy) {
            return;
        }
        if (this.isMoving) {
            this.moveByRadian(dt);
        }
        else {
            this.circuitous(dt);
        }
    }

    /**
     * 绕圆形圆周运动，当前运动的参数在本地中，用setAnchorPlanet或setAnchorInfo设置
     * @param dt 时间间隔
     */
    circuitous(dt) {
        // console.log(this.anchorPlanet.ObjSprite.spriteFrame);
        this.updateRadius();
        if (this.circleRadius == 1)
            return;
        // console.log({radius:this.circleRadius});
        this.radian += dt * this.shipSpeed;
        this.radian = this.radian > 4 * Math.PI ? this.radian - 4 * Math.PI : this.radian;
        let x = this.circleRadius * Math.cos(this.radian) + this.anchorPlanet.x;
        let y = this.circleRadius * Math.sin(this.radian) + this.anchorPlanet.y;
        //console.log(x);
        this.ObjSprite.node.setPosition(x, y);
        this.supportLineNode.rotation = 90 - (this.radian * 180 / Math.PI);
        this.supportLineNode.active = true;
    }

    /**
     * 用星球类来更新圆周运动参数
     * @param anchorPlanet 用来传递参数的星球类
     */
    setAnchorPlanet(anchorPlanet: FlyObj = null, isFirst = false): void {
        if (!anchorPlanet) {
            const anchorInfo: NodeInfoPara =
            {
                x: 0,
                y: 0,
                scaleX: 1,
                scaleY: 1,
                width: 10
            };
            this.anchorPlanet = anchorInfo;
        }
        else {
            const anchorInfo: NodeInfoPara =
            {
                x: anchorPlanet.ObjSprite.node.x,
                y: anchorPlanet.ObjSprite.node.y,
                scaleX: anchorPlanet.ObjSprite.node.scaleX,
                scaleY: anchorPlanet.ObjSprite.node.scaleY,
                width: anchorPlanet.ObjSprite.node.width
            };
            this.anchorPlanet = anchorInfo;
            //console.log(anchorInfo )
        }
        // console.log(!anchorPlanet);

        this.updateRadius();
        // console.log({width1: this.node.width, width2: this.anchorPlanet.width})

        let deltaX = this.node.x - this.anchorPlanet.x;
        let deltaY = this.node.y - this.anchorPlanet.y;

        if (isFirst) {
            this.ObjSprite.node.setPosition(this.anchorPlanet.x, this.anchorPlanet.y - this.circleRadius);
            this.radian = - Math.PI / 2;
            this.isMoving = false;
            this.node.active = true;
            this.isDestroy = false;
        }
        else {
            this.radian = Math.sign(deltaX) > 0 ? Math.atan(deltaY / deltaX) : (Math.atan(deltaY / deltaX) - Math.PI);
        }
    }

    updateRadius() {
        this.circleRadius = (this.node.width + this.anchorPlanet.width) / 2 - 1;
    }

    /**
     * 用指定接口来更新圆周运动参数
     * @param anchorPlanet 用来传递参数的接口
     */
    setAnchorInfo(anchorInfo: NodeInfoPara) {
        this.anchorPlanet = anchorInfo;
        this.updateRadius();
        this.radian = - Math.PI / 2;
        // this.node.setPosition(this.anchorPlanet.x, this.anchorPlanet.y - this.circleRadius);
    }

    moveByRadian(dt, radian: number = this.radian) {
        this.radian = radian;
        let x = this.shipSpeed * 150 * dt * Math.cos(this.radian) + this.node.x;
        let y = this.shipSpeed * 150 * dt * Math.sin(this.radian) + this.node.y;
        if (global.gameMode == 0) {
            x = this.shipSpeed * 100 * dt * Math.cos(this.radian) + this.node.x;
            y = this.shipSpeed * 100 * dt * Math.sin(this.radian) + this.node.y;
        }
        // console.log({x:x, y:y});
        //console.log(x);
        // this.ObjSprite.node.runAction(cc.moveTo(dt, new cc.Vec2(x, y)));
        this.ObjSprite.node.setPosition(x, y);
        this.supportLineNode.active = false;
    }

    onCollisionEnter(other, self) {
        // console.log({other: other.node.name, other_father: other.node.parent.name, self:self.node.name, father: self.node.parent.name});

        if (other.name == "Planet" || other.name == "SpaceStation") {
            // console.log("Planet");
            if (this.gamegrabsound) cc.audioEngine.playEffect(this.gamegrabsound, false);

            let otherStar = other.node.getComponent(other.node.name);
            let selfSpaceShip: SpaceShip = self.node.getComponent(self.node.name);
            selfSpaceShip.setAnchorPlanet(otherStar);
            this.isMoving = false;
            if (global.gameMode == 1) {
                if (!(otherStar.firstPlanet != undefined && otherStar.firstPlanet)) {
                    this.node.parent.getComponent('Game2').updateScore();
                }
            }
        }
        else if (other.name == "FixedStar") {
            // console.log("!~!!!!!!!!!!");
            let otherStar = other.node.getComponent(other.node.name);
            let selfSpaceShip: SpaceShip = self.node.getComponent(self.node.name);
            selfSpaceShip.setAnchorPlanet(otherStar);
            this.isMoving = false;
            this.isDestroy = true;
            this.node.active = false;
        }
        else if (other.name == "Canvas") {
            // console.log("Canvas");
        }
        // console.log(other.name);
        //console.log('on collision stay');
    }

    // update (dt) {}
}

